const app = getApp()
import util from '../../../../utils/util'
import {
    ReportDetail,
    SaveReportData
} from '../../../../config/api'

Page({
    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        currDate: '',
        imgs: [],
        count: 0,
        compressImgsSizeArr: [],
        dialogShow: false,
        buttons: [{
            text: '取消'
        }, {
            text: '确定'
        }],
        temp: 0,
        state: 1,
        items: [{
                value: '1',
                name: '很正常',
                checked: 'true'
            },
            {
                value: '2',
                name: '有不适'
            },
        ],
        report_time: '',
        dayArr: [],
        remark:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            id: options.id
        })
        this.getYearMonth();
        util.apiRequest(ReportDetail, {
            id: options.id
        }, null).then(r => {
            console.log(r)
            this.setData({
                data: r.data.data
            })
            if (r.data.data.report.length) {
                this.setData({
                    imgs: r.data.data.report
                })
            }
            let dayArr = [];
            for (let i = 0, length = r.data.data.wait_day; i < length; i++) {
                var dateTime = new Date(r.data.data.return_at);
                dateTime = dateTime.setDate(dateTime.getDate() + i);
                dateTime = new Date(dateTime);
                console.log("dateTime:", dateTime)
                let date = util.formatTime(dateTime);
                var endindex = date.indexOf(" ");
                date = date.substring(0, endindex);
                let obj = {
                    state: 1,
                    temp: (new Date().getTime() - new Date(date).getTime()) > 0 ? 0 : -1,
                    daydate: date
                };
                dayArr.push(obj)
            }
            console.log("dayArr:", dayArr)

            if (r.data.data.log.length != 0) {
                let logs = r.data.data.log;
                for (let i = 0, length = logs.length; i < length; i++) {
                    for (let d = 0, length = dayArr.length; d < length; d++) {
                        if (logs[i].time == dayArr[d].daydate) {
                            dayArr[d]['state'] = logs[i].state;
                            dayArr[d]['temp'] = logs[i].temp;
                        }
                    }
                }
            }
            this.setData({
                dayArr
            })
        })
    },

    getYearMonth() { // 计算当前获取年月日
        var myDate = new Date();
        var tYear = myDate.getFullYear();
        var tMonth = myDate.getMonth();
        var tday = myDate.getDate()
        var m = tMonth + 1;
        if (m.toString().length == 1) {
            m = "0" + m;
        }
        if (tday.toString().length == 1) {
            tday = "0" + tday;
        }
        let currDate = tYear + '-' + m + '-' + tday
        console.log('当前日期', currDate)
        this.setData({
            currDate
        })
    },

    // 上传图片
    chooseImg: function (e) {
        //console.log('选择图片e', e)
        var that = this;
        var imgs = this.data.imgs;
        let uploadFile = ''; //最后处理完，图片上传的图片地址

        wx.chooseImage({
            count: 9, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                //  console.log('图片', res.tempFilePaths)
                var tempFilePaths = res.tempFilePaths;
                // var imgs = [];
                wx.showLoading({
                    title: '上传中',
                })
                for (let i = 0; i < tempFilePaths.length; i++) {
                    let index = that.data.count;
                    let canvasId = 'canvasId' + index; // canvas id
                    console.log('canvasId', canvasId)
                    //获得原始图片大小
                    wx.getImageInfo({
                        src: tempFilePaths[i],
                        success(res) {
                            console.log('原始图片r', res)
                            var originWidth, originHeight;
                            originHeight = res.height;
                            originWidth = res.width;
                            //压缩比例
                            // 最大尺寸限制
                            var maxWidth = 800,
                                maxHeight = 600;
                            // 目标尺寸
                            var targetWidth = originWidth,
                                targetHeight = originHeight;

                            //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
                            if (originWidth > maxWidth || originHeight > maxHeight) {
                                console.log('图片过大需要压缩')
                                if (originWidth / originHeight > maxWidth / maxHeight) {
                                    // 要求宽度*(原生图片比例)=新图片尺寸
                                    targetWidth = maxWidth;
                                    targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                                } else {
                                    targetHeight = maxHeight;
                                    targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                                }
                            }

                            //更新canvas大小
                            let compressObj = {},
                                compressImgsSizeArr = that.data.compressImgsSizeArr;
                            compressObj['index'] = index;
                            compressObj['cw'] = targetWidth;
                            compressObj['ch'] = targetHeight;
                            compressImgsSizeArr.push(compressObj)

                            that.setData({
                                compressImgsSizeArr: compressImgsSizeArr
                            });

                            //尝试压缩文件，创建 canvas
                            var ctx = wx.createCanvasContext(canvasId);
                            ctx.clearRect(0, 0, targetWidth, targetHeight);
                            ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

                            //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

                            //保存图片
                            ctx.draw(false,
                                setTimeout(function () {
                                    wx.canvasToTempFilePath({
                                        canvasId: canvasId,
                                        width: targetWidth,
                                        height: targetHeight,
                                        destWidth: targetWidth,
                                        destHeight: targetHeight,
                                        quality: 0.4,
                                        success: (res) => {
                                            console.log('压缩后', res)
                                            uploadFile = res.tempFilePath;
                                            wx.uploadFile({
                                                url: app.globalData.baseURL + '/api/GriderProgramApi/uploadReport',
                                                filePath: uploadFile,
                                                name: 'file',
                                                header: {
                                                    "Content-Type": "multipart/form-data"
                                                },
                                                formData: {
                                                    'id': that.data.id,
                                                    'file': tempFilePaths
                                                },
                                                success(res) {
                                                    console.log('图片上传成功', res)
                                                    let data = JSON.parse(res.data);
                                                    if (res.statusCode == 200) {
                                                        var imgSrc = data.data;
                                                        console.log('图片服务器地址', imgSrc)
                                                        // that.data.imgs.push(imgSrc);
                                                        //   console.log('图片数组', imgs)
                                                        that.setData({
                                                            imgs: imgSrc
                                                        })
                                                        wx.hideLoading()
                                                    }
                                                },
                                                fail(res) {
                                                    console.log('上传失败')
                                                }
                                            })

                                        },
                                        fail: (err) => {
                                            console.error(err)
                                        }
                                    }, this)
                                }, 1000)
                            );

                        }
                    })

                    let count = ++that.data.count;
                    console.log('++count', count)
                    that.setData({
                        count: count
                    })
                    //console.log('循环后count', that.data.count)
                }
            }
        });
    },

    // 删除图片
    deleteImg: function (e) {
        var imgs = this.data.imgs;
        var compressImgsSizeArr = this.data.compressImgsSizeArr;
        var index = e.currentTarget.dataset.index;
        imgs.splice(index, 1);
        compressImgsSizeArr.splice(index, 1);
        this.setData({
            imgs: imgs,
            compressImgsSizeArr: compressImgsSizeArr
        })
    },

    // 预览图片
    previewImg: function (e) {
        let that = this;
        //获取当前图片的下标
        var index = e.currentTarget.dataset.index;
        console.log('预览index', index)
        //所有图片
        var imgType = e.currentTarget.dataset.imgtype;
        var imgs = this.data.imgs;

        console.log('预览时imgs', imgs)
        console.log(imgs[index])
        wx.previewImage({
            //当前显示图片
            current: imgs[index],
            //所有图片
            urls: imgs
        })
    },

    onReport(e) {
        this.setData({
            dialogShow: true,
            report_time: e.currentTarget.dataset.time
        })
    },

    inputChange(e) {
        this.setData({
            temp: e.detail.value
        })
    },

    radioChange(e) {
        console.log('radio发生change事件：', e.detail.value);
        this.setData({
            state: e.detail.value
        })
        const items = this.data.items;
        for (let i = 0, len = items.length; i < len; ++i) {
            items[i].checked = items[i].value == e.detail.value;
        }
    },

    bindTextAreaBlur: function (e) {
        console.log(e.detail.value)
        this.setData({
            remark:e.detail.value
        })
    },

    tapDialogButton(e) {
        console.log(e.detail.item.text)
        if (e.detail.item.text == "确定") {
            if (!this.data.temp) {
                wx.showToast({
                    icon: "none",
                    title: '请填写体温',
                })
                return;
            }
            let param = {
                rid: this.data.id,
                temp: this.data.temp,
                time: this.data.report_time,
                state: this.data.state,
                remark:this.data.remark
            }
            util.apiRequest(SaveReportData, param).then(r => {
                console.log(r)
                if (r.data.code) {
                    this.setData({
                        dialogShow: false
                    })
                }
                wx.showToast({
                    icon: 'none',
                    title: r.data.info
                })
                wx.redirectTo({
                    url: '/pages/mine/epidemic-reporting/detail/detail?id=' + this.data.id,
                })
            })

        } else {
            this.setData({
                dialogShow: false
            })
        }
    },



    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})